<template>
  <div class="hc-custom-map">
    <el-autocomplete
      v-model="state"
      v-if="defaultDraw == null"
      :fetch-suggestions="querySearchAsync"
      placeholder="请输入地址"
      style="width: 70%;"
      @select="handleSelect"
    ></el-autocomplete>
    <div class="map-container" id="map-container"></div>
    <div class="draw-buttons" v-if="showControl">
      <!-- <div :class="['toolItem', activeType == 'marker' ? 'active' : '']" id="marker" title="点标记" @click="drawClick('marker')"></div> -->
      <div :class="['toolItem', activeType == 'polygon' ? 'active' : '']" id="polygon" title="多边形" @click="drawClick('polygon')"></div>
      <div :class="['toolItem', activeType == 'rectangle' ? 'active' : '']" id="rectangle" title="矩形" @click="drawClick('rectangle')"></div>
      <!-- <div @click="drawCircle" class="button-draw">绘制圆形</div> -->
      <!-- <el-button type="primary" size="mini" @click="drawRectangle">绘制矩形</el-button>
      <el-button type="primary" size="mini" @click="drawPolygon">绘制多边形</el-button>
      <el-button type="primary" size="mini" @click="drawClean">清除</el-button> -->
    </div>
    <div class="draw-tip" v-if="defaultDraw == null">
      <div>绘制: 鼠标左键单击及移动即可绘制图形</div>
      <div>鼠标左键双击即可结束绘制，多边形会自动闭合，圆形、矩形单击即可结束</div>
      <div>中断: 绘制过程中按下esc键可中断该过程</div>
    </div>
  </div>
</template>

<script>
import unit from './unit';
import { addressToTMap, SearchAddress } from '../OpenMap/TMap'

export default {
  name: "mapView",
  components: {},
  props: {
    showControl: {
      type: Boolean,
      default: true
    },
    defaultDraw: {
      type: Object,
      default: null
    },
    defaultXxdz: {
      type: String,
      default: ""
    }
  },
  data()
  {
    return {
      map: null,
      drawControl: null,
      drawLayerGroup: null,
      editor: null,
      activeType: "marker",
      // 中心点坐标
      centerPoint: [30.153848, 114.995255],
      state: '',
      timeout:  null
    }
  },
  watch: {
    defaultDraw: function (newVal, oldVal)
    {
      if (oldVal)
      {
        this.drawClean()
        unit.map.drawMap(newVal, this.map, this.drawLayerGroup)
      }
    }
  },
  methods: {
    drawClick(P_Type)
    {
      this.activeType = P_Type
      this.editor.setActiveOverlay(P_Type)
      this.editor.enable(); // 是否启用 disable 停用 enable 启用
    },
    drawCreatedBack(event)
    {
      let that = unit.map
      let area = ''
      const {layer, layerType} = event;
      if (layerType === "polygon" || layerType === "rectangle")
      {
        //layer.getLatLngs()得到的多边形的经纬度集合，多边形得到的是一个二维数组，这里要取里面的数组，一定要注意
        let latlng = layer.getLatLngs()[0];
        //一个自定义的计算面积的函数
        area = that.formatArea(latlng);
        that.addMeasureMarker(area, [latlng[0].lat, latlng[0].lng], this.drawLayerGroup);//把画图之后计算的结果添加到地图上
      }
      else if (layerType === "polyline")
      {
        //polyline得到的是一个一维数组，直接使用
        let latlng = layer.getLatLngs();
        //一个自定义的计算长度的函数
        let distance = that.formatLength(latlng);
        that.addMeasureMarker(distance, [latlng[0].lat, latlng[0].lng], this.drawLayerGroup);
      }
      else if (layerType === "circle")
      {
        //polyline得到的是一个一维数组，直接使用
        let radius = layer.getRadius();
        let latLng = layer.getLatLng()
        //一个自定义的计算长度的函数
        area = that.formatCircleArea(radius);
        that.addMeasureMarker(area, [latLng.lat, latLng.lng], this.drawLayerGroup);
      }
      this.$emit('drawCreatedBack', {
        latlng: layerType === "circle" ? layer.getLatLng() : layer.getLatLngs(),
        radius: layerType === "circle" ? layer.getRadius() : '',
        area: area,
        layerType
      })
      this.drawLayerGroup.addLayer(layer);
    },
    drawPolygon()
    {
      this.drawObj = new L.Draw.Polygon(this.map, this.drawControl.options.draw.polygon);
      this.drawObj.enable();
    },
    drawRectangle()
    {
      this.drawObj = new L.Draw.Rectangle(this.map, this.drawControl.options.draw.rectangle);
      this.drawObj.enable();
    },
    drawCircle()
    {
      this.drawObj = new L.Draw.Circle(this.map, this.drawControl.options.draw.circle);
      this.drawObj.enable();
    },
    drawClean()
    {
      // 删除全部绘制的图层
      if (this.drawLayerGroup)
      {
        this.drawLayerGroup.clearLayers();
      }
      // 取消绘制操作
      if (this.drawObj)
      {
        this.drawObj.disable();
      }
    },
    // 初始化地图
    initMap()
    {
      this.map = new TMap.Map(document.getElementById('map-container'), {
        center: this.centerPoint, // 设置地图中心点坐标
        zoom: 16.5,  // 设置地图缩放级别
        disableDefaultUI: true, // 禁用默认UI
      })
      var geometries = []
      var geometriesMarker = []
      console.log(this.defaultDraw, 'defaultDraw')
      if (this.defaultDraw)
      {
        this.defaultDraw.latlng.map((item, index) => {
          if (item.length > 0)
          {
            var path = []
            item.map(tmp => {
              path.push(
                new TMap.LatLng(tmp.lat, tmp.lng)
              )
            })
            geometries.push({
              id: `${this.defaultDraw.layerType}${index}`,
              styleId: 'polygon',  // 样式id
              paths: path,  // 多边形的位置信息
              properties: {
                // 多边形的属性数据
                title: ''
              }
            })
          }
        })
        if (this.defaultDraw.ldjwdMarker && this.defaultDraw.ldjwdMarker.length > 0)
        {
          this.defaultDraw.ldjwdMarker.map((child,i) => {
            if (child.ldjwd)
            {
              child.ldjwd = typeof child.ldjwd == 'string' ? JSON.parse(child.ldjwd) : child.ldjwd
              geometriesMarker.push({
                "id": `marker${i}`,
                "styleId": 'myStyle', // 指定样式id
                "position": new TMap.LatLng(child.ldjwd.lat || child.ldjwd.latitude, child.ldjwd.lng || child.ldjwd.longitude),// 点标记坐标位置
                "properties": { // 自定义属性
                  "title": child.ldmc
                }
              })
            }
          })
        }
      }
      // 标记
      var marker = new TMap.MultiMarker({
        map: this.map,
        // 样式定义
        styles: {
          "myStyle": new TMap.MarkerStyle({
            "width": 25,
            "height": 25
          })
        },
        geometries: geometriesMarker
      })
      // 多边形
      var polygon = new TMap.MultiPolygon({
        map: this.map,
        styles: {
          polygon: new TMap.PolygonStyle({
            color: 'rgba(255,255,255,0.5)',
            showBorder: true,
            borderColor: '#3388ff'  // 边线颜色
          })
        },
        geometries: geometries
      })
      // 矩形
      var rectangle = new TMap.MultiRectangle({
        map: this.map
      })
      this.editor = new TMap.tools.GeometryEditor({
        map: this.map,
        overlayList: [
          // {
          //   overlay: marker,
          //   id: 'marker'
          // },
          {
            overlay: polygon,
            id: "polygon"
          },
          {
            overlay: rectangle,
            id: "rectangle"
          }
        ],
        actionMode: TMap.tools.constants.EDITOR_ACTION.DRAW, // 编辑器的工作模式
        activeOverlayId: 'marker', // 激活图层
        snappable: true,  // 开启吸附
      })
      // 监听绘制结束事件，获取绘制几何图形
      this.editor.on('draw_complete', (geometry) => {
        console.log(geometry, '绘制')
        var id = geometry.id
        if (this.editor.getActiveOverlay().id === 'polygon')
        {
          var geo = polygon.geometries.filter(item => item.id === id)
          console.log(geo, '绘制的多边形坐标')
          // 绘画结束后，停用编辑模式
          this.editor.disable();
          var area = TMap.geometry.computeArea(geometry.paths)
          area = (area / 1000).toFixed(2) + 'k㎡'
          console.log(area, '区域面积')
          this.$emit('drawCreatedBack', {
            latlng: [geometry.paths],
            radius: '',
            area: area,
            layerType: this.activeType
          })
        }
        if (this.editor.getActiveOverlay().id === 'rectangle')
        {
          var geo = rectangle.geometries.filter(item => item.id === id)
          console.log(geo, '绘制的矩形坐标')
          var area = TMap.geometry.computeArea(geo[0].paths)
          console.log(area, '区域面积1')
          this.$emit('drawCreatedBack', {
            latlng: [geo[0].paths],
            radius: '',
            area: area,
            layerType: this.activeType
          })
        }
        if (this.editor.getActiveOverlay().id === 'marker')
        {
          var geo = marker.geometries.filter(item => item.id === id)
          console.log(geo, '绘制的定位坐标')
        }
      })
    },
    // 加载地图sdk
    loadMapSDK()
    {
      return new Promise((resolve, reject) => {
        if (window.TMap) return resolve(); // 避免重复加载

        // 先加载主库
        const mainScript = document.createElement('script');
        mainScript.src = 'https://map.qq.com/api/gljs?v=1.exp&key=KVZBZ-Y7BKJ-YJSFR-DPR2M-LRW5O-EIFW6'
        // 主库加载成功后，再加载工具库
        mainScript.onload = () => {
          const toolScript = document.createElement("script")
          toolScript.src = 'https://map.qq.com/api/gljs?v=1.exp&key=KVZBZ-Y7BKJ-YJSFR-DPR2M-LRW5O-EIFW6&libraries=tools,geometry'
          toolScript.onload = resolve;
          toolScript.onerror = reject;
          document.head.appendChild(toolScript);
        }
        mainScript.onerror = reject;
        document.head.appendChild(mainScript);
      })
    },
    loadAll()
    {
      var restaurants = []
      addressToTMap(this.defaultXxdz).then(res => {
        console.log(res, 'res')
        if (res) {
          restaurants.push({
            value: res.title,
            address: res.address_components.province + res.address_components.city + res.address_components.district +
              res.address_components.street + res.address_components.street_number + res.title,
          })
        }
      })
      return restaurants;
    },
    // 搜索
    search(queryString)
    {
      var result = []
      if (queryString)
      {
        SearchAddress(queryString).then(res => {
          console.log(res, 'res')
          if (res.length > 0)
          {
            res.map(pre_item => {
              result.push({
                value: pre_item.title + ' [' + pre_item.category + ']',
                address: pre_item.address,
                location: pre_item.location
              })
            })
          }
        })
      }
      return result;
    },
    querySearchAsync(queryString, cb)
    {
      var restaurants = this.search(queryString);
      
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
        
        cb(restaurants);
      }, 500);
    },
    createStateFilter(queryString) 
    {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      console.log(item);
      this.centerPoint = [item.location.lat, item.location.lng]
      this.$nextTick(() => {
        this.updateCenter(this.centerPoint) // 使用更新方法而不是重新初始化
      })
    },
    // 更新中心点
    updateCenter(point) {
      if (this.map) {
        // 正确创建LatLng对象
        const newCenter = new TMap.LatLng(point[0], point[1])
        
        // 方法一：直接设置中心点
        this.map.setCenter(newCenter)
        
        // 方法二：平滑移动（推荐）
        // this.map.panTo(newCenter)
        
        // 可选的缩放调整
        this.map.setZoom(16.5)
      }
    }
  },
  async mounted()
  {
    this.restaurants = this.loadAll()
    await this.loadMapSDK()
    if (this.defaultDraw)
    {
      var firstLatlng = this.defaultDraw.latlng[0] || []
      if (firstLatlng.length > 0)
      {
        this.centerPoint = [firstLatlng[0].lat,firstLatlng[0].lng]
      }
      this.initMap()
    }
    if (this.defaultXxdz)
    {
      addressToTMap(this.defaultXxdz).then(res => {
        if (res)
        {
          this.centerPoint = [res.location.lat, res.location.lng]
        }
        this.initMap()
      })
    }
    else
    {
      this.initMap()
    }
    return
    this.$nextTick(() =>
    {
      // 异步加载地图
      const mapScript = document.createElement("script")
      mapScript.type = 'text/javascript'
      mapScript.src = 'https://map.qq.com/api/gljs?v=1.exp&key=KVZBZ-Y7BKJ-YJSFR-DPR2M-LRW5O-EIFW6'
      const mapToolScript = document.createElement("script")
      mapToolScript.type = 'text/javascript'
      mapToolScript.src = 'https://map.qq.com/api/gljs?v=1.exp&key=KVZBZ-Y7BKJ-YJSFR-DPR2M-LRW5O-EIFW6&libraries=tools,geometry'
      document.body.appendChild(mapScript)
      document.body.appendChild(mapToolScript)
      mapScript.onload = () => {
        console.log('mapScript 加载完毕')
        // 加载完成后初始化地图
        console.log(this.defaultXxdz, 'defaultXxdz')
        if (this.defaultXxdz)
        {
          addressToTMap(this.defaultXxdz).then(res => {
            if (res)
            {
              this.centerPoint = [res.location.lat, res.location.lng]
            }
            this.initMap()
          })
        }
        else
        {
          this.$nextTick(() => {
            this.initMap()
          })
        }
        if (this.defaultDraw)
        {
          var firstLatlng = this.defaultDraw.latlng[0] || []
          if (firstLatlng.length > 0)
          {
            this.centerPoint = [firstLatlng[0].lat,firstLatlng[0].lng]
          }
          this.initMap()
        }
      }
      return
      this.map = unit.map.createMap("map-container", {crs: L.CRS.EPSG4326});
      // 设施地图视图 中心位置
      this.map.setView([30.449148, 114.358198], 13);
      // 加载 open street map和mapbox 图层服务
      unit.map.createTDTWMTSLayer(this.map, {maxZoom: 17});
      this.drawLayerGroup = unit.map.createFeatureGroup(this.map)
      this.drawControl = unit.map.createDrawControl(this.map, this.drawCreatedBack, {
        draw: {
          polyline: true,
          polygon: true,
          rectangle: true,
          circle: true,
          marker: true,
        }
      })
      unit.map.createMapArea(this.map, this.drawLayerGroup);
      console.log(this.defaultDraw,"============cs")
      if (this.defaultDraw)
      {
        unit.map.drawMap(this.defaultDraw, this.map, this.drawLayerGroup)
        
        if (this.defaultDraw.ldjwdMarker.length > 0)
        {
          var ldids = []
          this.defaultDraw.ldjwdMarker.map(item => {
            if (item.ldjwd)
            {
              item.layerType = 'marker'
              item.title = item.ldmc
              item.latLng = JSON.parse(item.ldjwd)
              ldids.push(item.ldid)
              item.ldids = ldids
              item.type = 'current'
              unit.map.drawMap(item, this.map, this.drawLayerGroup, this)
            }
          })
        }
      }
    })

  }
}
</script>
<style scoped>
.map-container {
  position: absolute;
  left: 0;
  top: 40px;
  width: 100%;
  height: 100%;
}

.draw-buttons {
  position: absolute;
  z-index: 99999;
  right: 90px;
  top: 50px;
  display: flex;
}
.draw-tip {
  position: absolute;
}
.toolItem {
  width: 30px;
  height: 30px;
  float: left;
  margin: 1px;
  padding: 4px;
  border-radius: 3px;
  background-size: 30px 30px;
  background-position: center;
  background-repeat: no-repeat;
  box-shadow: 0 1px 2px 0 #e4e7ef;
  background-color: #ffffff;
  border: 1px solid #ffffff;
}
.toolItem:hover {
  border-color: #789cff;
}
.active {
  border-color: #d5dff2;
  background-color: #d5dff2;
}
#marker {
  background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/marker_editor.png');
}
#polygon {
  background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/polygon.png');
}
#rectangle {
  background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/rectangle.png');
}
</style>
